package com.ay.weixin.fdc.front.usercenter.event;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.Calendar;

import javax.servlet.ServletException;

import org.lizar.config.Config;
import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;
import org.lizar.json.JObject;
import org.lizar.json.util.JSONParser;
import org.lizar.log.Log;
import org.lizar.log.Logger;
import org.lizar.util.StringHelper;
import org.lizar.util.https.Https;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.fdc.boss.user.db.UserDao;
import com.ay.weixin.fdc.boss.user.db.WeiXinInfoDao;
import com.ay.weixin.fdc.boss.user.domain.UserWeiXinInfo;

public class UserInfoAccess extends Event {
	private UserDao user_dao;
	private WeiXinInfoDao weixin_dao;
	private Log log=Logger.newInstance(this.getClass());
	@Override
	public void init_property() throws Exception {
		user_dao=Container.get(UserDao.class);
		weixin_dao=Container.get(WeiXinInfoDao.class);
		
	}

	@Override
	public String default_handling_path() {
		return "/usercenter/openid/access/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		long  wxproject_id=el.queryPathInt(3);
		System.out.println("project_id:"+wxproject_id);
		
		if(el.queryPathCheck(4, "")){
			open_id_check(el,null,wxproject_id);
		}else if(el.queryPathCheck(4, "openid")){
			openid(el,wxproject_id);
		}else if(el.queryPathCheck(4, "user_info")){
			user_info(el,wxproject_id);
		}
	}
	
	public void open_id_check(EventLoader el,String forward_url,long wxproject_id,String queryParam) throws IOException{
		UserWeiXinInfo weixin_info=el.getSessionAttr("weixin_info",UserWeiXinInfo.class);
		if(StringHelper.isNull(forward_url)){
			forward_url=Keys.getStr("forward.user_login_default_url");
		}
		if(weixin_info==null||
				(StringHelper.equals(ProjectConfig.getStr(wxproject_id,"weixin_api_user.scope_level"), "snsapi_userinfo")&&StringHelper.isNull(weixin_info.getNickname()))){
			
			String redirect_url=null;
			String code_url=null;
			if(StringHelper.equals(ProjectConfig.getStr(wxproject_id,"weixin_api_user.scope_level"), "snsapi_userinfo")){
				redirect_url=Config.xpath("server_info.root")+"/usercenter/openid/access/user_info?forward_url="+forward_url+wxproject_id+queryParam;
				code_url=String.format(Keys.getStr("weixin.code_retreive_url"),ProjectConfig.getStr(wxproject_id,"sys.AppId"), URLEncoder.encode(redirect_url));
			}else{
				redirect_url=Config.xpath("server_info.root")+"/usercenter/openid/access/openid?forward_url="+forward_url+wxproject_id+queryParam;
				code_url=String.format(Keys.getStr("weixin.code_base_retreive_url"),ProjectConfig.getStr(wxproject_id,"sys.AppId"), URLEncoder.encode(redirect_url));
			}
			
			System.out.println("to retreive:"+code_url);
			el.response(code_url);
			return;
		}
		el.text("invalid visit");
	}
	
	public void open_id_check(EventLoader el,String forward_url,long wxproject_id) throws IOException{
		open_id_check( el, forward_url, wxproject_id,"");
	}
	
	
	private void openid(EventLoader el,long wxproject_id) throws IOException{
		String code=el.getStr("code");
		String forward_url=el.getStr("forward_url");
		
		if(StringHelper.isNull(code)){
			el.text(el.i18("auth.failed")+":"+"请重新授权，(亲爱的经纪人，我们需要您的公开信息，才能够进一步与您沟通)");
			return;
		}
		String url=String.format(Keys.getStr("weixin.access_token_url"),ProjectConfig.getStr(wxproject_id,"sys.AppId"),ProjectConfig.getStr(wxproject_id,"AppSecret"),code);
		
		String result=null;
		try{
			System.out.println("try:"+url);
			result=Https.GetMethod(url);
			System.out.println("get:"+result);
		}catch(Exception e){
			e.printStackTrace();
			el.text(el.i18("need.auth")+":"+e.getLocalizedMessage());
			return;
		}
		
		if(StringHelper.isNull(result)){
			el.text(el.i18("auth.failed"));
			return;
		}
		JObject data=(JObject)JSONParser.parse(result);
		if(data.getInt("errcode")>0){
			el.text(el.i18("auth.failed")+":"+data.getStr("errmsg")+"("+data.getInt("errcode")+")");
			return;
		}
		
		String openid=data.getStr("openid");
		
		UserWeiXinInfo weixin=null;
		
		try {
			weixin=weixin_dao.get(openid);
		} catch (SQLException e) {
			e.printStackTrace();
			el.text(el.i18("auth.failed")+":"+e.getLocalizedMessage());
			return;
		}
		
		//从未授权过
		if(weixin==null){
			weixin=new UserWeiXinInfo();
			weixin.setId(data.getStr("openid"));
			weixin.setUpdate_date(Calendar.getInstance().getTime());
			try {
				weixin_dao.insert(weixin);
			} catch (SQLException e) {
				e.printStackTrace();
				el.text(el.i18("need.auth")+":"+e.getLocalizedMessage());
				return;
			}
		}
		el.setSessionAttr("weixin_info", weixin);
		if(StringHelper.isNull(forward_url)){
			forward_url=Keys.getStr("forward.user_login_default_url");
		}
		el.response_to_root(forward_url+wxproject_id);
	}
	
	

	private JObject get_user_info(EventLoader el,String access_token,String openid) throws IOException{
		String result=null;
		String user_url=String.format(Keys.getStr("weixin.user_info_url"),access_token,openid);
		
		System.out.println("try:"+user_url);
		try{
			result=null;
			result=Https.GetMethod(user_url);
			System.out.println("get result:"+result);
		}catch(Exception e){
			e.printStackTrace();
			el.text(el.i18("auth.failed")+":"+e.getLocalizedMessage());
			return null;
		}
		JObject data=null;
		if(StringHelper.isNotNull(result)){
			data=(JObject)JSONParser.parse(result);
			if(data.getInt("errcode")>0){
				log.error(el.i18("auth.failed")+":"+data.getStr("errmsg")+"("+data.getInt("errcode")+")");
				el.text(el.i18("auth.failed")+":"+"请重新授权，(亲爱的经纪人，我们需要您的公开信息，才能够进一步与您沟通)");
				return null;
			}
		}
		return data;
	}
	
	private void user_info(EventLoader el,long wxproject_id) throws IOException{
		String code=el.getStr("code");
		String forward_url=el.getStr("forward_url");
		
		if(StringHelper.isNull(code)){
			el.text(el.i18("need.auth"));
			return;
		}
		String url=String.format(Keys.getStr("weixin.access_token_url"),ProjectConfig.getStr(wxproject_id,"sys.AppId"),ProjectConfig.getStr(wxproject_id,"AppSecret"),code);
		
		String result=null;
		try{
			System.out.println("try:"+url);
			result=Https.GetMethod(url);
			System.out.println("get:"+result);
		}catch(Exception e){
			e.printStackTrace();
			el.text(el.i18("need.auth")+":"+e.getLocalizedMessage());
			return;
		}
		
		if(StringHelper.isNull(result)){
			el.text(el.i18("auth.failed"));
			return;
		}
		JObject data=(JObject)JSONParser.parse(result);
		if(data.getInt("errcode")>0){
			el.text(el.i18("auth.failed")+":"+data.getStr("errmsg")+"("+data.getInt("errcode")+")");
			return;
		}
		
		String scope=data.getStr("scope");
		if(scope==null||!scope.contains("snsapi_userinfo")){
			el.text("invalid visit");
			return;
		}
		
		System.out.println("openid:"+data.getStr("openid"));
		
		UserWeiXinInfo weixin=null;
		
		try {
			weixin=weixin_dao.get(data.getStr("openid"));
		} catch (SQLException e) {
			e.printStackTrace();
			el.text(el.i18("auth.failed")+":"+e.getLocalizedMessage());
			return;
		}
		
		data=get_user_info(el,data.getStr("access_token"),data.getStr("openid"));
		//已跳转，不再跳转
		if(data==null){
			return;
		}
		
		boolean weixin_insert=false;
		
		if(weixin==null){
			weixin=new UserWeiXinInfo();
			weixin.setAccess_token(data.getStr("access_token"));
			weixin.setUpdate_date(Calendar.getInstance().getTime());
			weixin.setCity(data.getStr("city"));
			weixin.setCountry(data.getStr("country"));
			weixin.setNickname(data.getStr("nickname").trim());
			weixin.setProvince(data.getStr("province"));
			weixin.setHeadimgurl(data.getStr("headimgurl"));
			weixin.setId(data.getStr("openid"));
			weixin.setSex(data.getInt("sex")+"");
			weixin_insert=true;
		}else{
			weixin.setAccess_token(data.getStr("access_token"));
			weixin.setUpdate_date(Calendar.getInstance().getTime());
			weixin.setCity(data.getStr("city"));
			weixin.setCountry(data.getStr("country"));
			weixin.setNickname(data.getStr("nickname").trim());
			weixin.setProvince(data.getStr("province"));
			weixin.setHeadimgurl(data.getStr("headimgurl"));
			weixin.setSex(data.getInt("sex")+"");
		}
		
		try {
			if(weixin_insert){
				weixin_dao.insert(weixin);
			}else{
				weixin_dao.update(weixin);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			el.text(el.i18("need.auth")+":"+e.getLocalizedMessage());
			return;
		}
		
		el.setSessionAttr("weixin_info", weixin);
		if(StringHelper.isNull(forward_url)){
			forward_url=Keys.getStr("forward.user_login_default_url");
		}
		el.response_to_root(forward_url+wxproject_id);
	}

}
